import cv2
import matplotlib.pyplot as plt

# 读取图像
image1 = cv2.imread('image1.jpg', cv2.IMREAD_GRAYSCALE)
image2 = cv2.imread('image2.jpg', cv2.IMREAD_GRAYSCALE)

# 创建SIFT特征点检测器
sift = cv2.SIFT_create()

# 检测特征点和计算描述符
kp1, des1 = sift.detectAndCompute(image1, None)
kp2, des2 = sift.detectAndCompute(image2, None)

# FLANN匹配器参数
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)

# 创建FLANN匹配器对象
flann = cv2.FlannBasedMatcher(index_params, search_params)

# 匹配描述符
matches = flann.knnMatch(des1, des2, k=2)

# 过滤匹配结果
good_matches = []
for m, n in matches:
    if m.distance < 0.7 * n.distance:
        good_matches.append(m)

# 绘制匹配结果
image_matches = cv2.drawMatches(image1, kp1, image2, kp2, good_matches, None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

# 显示结果
plt.imshow(image_matches)
plt.title('FLANN Matcher')
plt.show()